package com.binary;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

public class EmployeeTest {

	public static void main(String[] args) throws Exception {
		String path = "C:" + File.separator + "aaa" + File.separator;
		File f = new File(path);
		if (!f.exists()) {
			f.mkdir();
		}
		String fileName = "emp1.bin";

		// 准备数据
		List<Employee> ls = new ArrayList<Employee>();

		final int AMOUT = 10;
		for (long i = 0; i < AMOUT; i++) {
			ls.add(new Employee(i, "克隆人-" + i, (int) (i % 100)));
		}

		// 写入
		DataOutputStream out = new DataOutputStream(new FileOutputStream(path
				+ fileName, true));
		for (Employee emp : ls) {
			 writeEmp(out, emp);
		}
		 // 挨个读取
		 RandomAccessFile in = new RandomAccessFile(path + fileName, "r");
		 int len = (int) (in.length() / Employee.RecordSize);
		 System.out.println(in.length());
		 for (long i = 0; i < len; i++) {
		 in.seek(i * Employee.RecordSize);
		 Employee emp = readEmp(in);
		 System.out.println(emp.toString());
		 }
	}

	private static void writeEmp(DataOutput out, Employee emp) throws Exception {
		writeString(emp.getName(), Employee.NameSize, out);
		out.writeLong(emp.getId());
		out.writeInt(emp.getAge());
	}

	/**
	 * 写入一个整数
	 * 
	 * @param out
	 * @param id
	 * @throws Exception
	 */
	private static void writeEmp(DataOutput out, long id) throws Exception {
		out.writeLong(id);
	}

	private static void writeEmp(DataOutput out, int id) throws Exception {
		out.writeInt(id);
	}

	private static Employee readEmp(DataInput in) throws Exception {
		String name = readString(Employee.NameSize, in);
		long sn = in.readLong();
		int age = in.readInt();

		return new Employee(sn, name, age);
	}

	// 写入最大长度为size的字符串，不足写0
	private static void writeString(String str, int size, DataOutput out)
			throws Exception {
		for (int i = 0; i < size; i++) {
			char c = 0;
			if (i < str.length()) {
				c = str.charAt(i);
			}
			out.writeChar(c);
		}
	}

	// 读入最大长度为size的字符串
	private static String readString(int size, DataInput in) throws Exception {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < size; i++) {
			char c = in.readChar();

			if (c == 0) {
				continue;
			} else {
				sb.append(c);
			}
		}

		return sb.toString();
	}
}
